﻿/// <summary>
/// 加入房间
/// </summary>
public class Game_JoinRoom1State : GameState
{
	static Game_JoinRoom1State _inst;

	public static Game_JoinRoom1State inst {
		get {
			if (_inst == null) {
				_inst = new Game_JoinRoom1State ();
			}
			return _inst;
		}
	}


	public override void Enter ()
	{
		DebugInfo.Log ("Enter Game_JoinRoom1State");

		RequestJoinRoom ();
	}

	public override void Leave ()
	{
		DebugInfo.Log ("Leave Game_JoinRoom1State");
	}

	public override bool ProcessPacket (IOMessage message)
	{
		switch (message.code) {
		case IOCmds.WS_CONN_OPEN:
                // 与服务器的连接打开
			UIRootController.inst.ShowMask (false);
			GameProcedure.inst.SwitchState (Game_JoinRoom2State.inst);
			return true;

		case IOCmds.SMSG_JOIN_ROOM:
			HandleJoinRoomFromMiddle (message);
			return true;

		case IOCmds.WS_CONN_CLOSED:
			// 连接失败或者/连接断开
			UIRootController.inst.ShowMask (true);
			if (NetIOController.inst.isGame) {
				NetIOController.inst.Connect (null);
			}
			return true;
		}

		return base.ProcessPacket (message);
	}

	/// <summary>
	/// 处理中央服务器发来的加入房间消息
	/// </summary>
	/// <param name="message"></param>
	void HandleJoinRoomFromMiddle (IOMessage message)
	{
		if (message.state == IOStates.STATE_OK) {
			GameDataKernel.inst.roomId = message.args.GetInt ("gsRoomId");
			GameDataKernel.inst.serverAddr = message.args.GetString ("gsAddr");

			UIRootController.inst.ShowMask (true);
			NetIOController.inst.isGame = true;
			NetIOController.inst.ConnectToNewURL (GameDataKernel.inst.serverAddr);
		} else {
			UIRootController.inst.ShowMask (false);
			UICommon_TipWindow.Popup ("房间不存在！");

			UIHome_JoinRoom.CloseWindow ();
			GameController.inst.SwitchTo (HomeProcedure.inst, false);
		}
	}
}
